package cn.itwen.star.graph.comfyui.client.config;

import cn.itwen.star.graph.comfyui.client.api.ComfyuiApi;
import cn.itwen.star.graph.comfyui.client.handle.ComfyuiMessageHandler;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.client.WebSocketClient;
import org.springframework.web.socket.client.WebSocketConnectionManager;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;

import java.time.Duration;

@Configuration
public class comfyuiConfig {

    @Bean
    public ComfyuiApi comfyuiApi() {
        // 创建一个日志拦截器
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        /*
        * 设置日志级别为 BODY，表示打印所有请求和响应的日志信息。
        *  - NONE：不输出
         - BASIC：输出基本摘要
         - HEADERS：输出头信息
           BODY：输出body数据
         */
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(Duration.ofSeconds(30))//设置连接超时时间
                .readTimeout(Duration.ofSeconds(30))//设置读取超时
                .retryOnConnectionFailure( true) // 设置是否重试
                .addInterceptor(loggingInterceptor) // 添加日志拦截器
                .build();

        // 创建一个 Retrofit 实例
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://127.0.0.1:8188") // 设置 API 的基础 URL
                .client(okHttpClient) // 设置 OkHttpClient
                .addConverterFactory(JacksonConverterFactory.create())// 添加转换工厂
                .build();
        //基于Retrofit创建一个接口代理对象
        return retrofit.create(ComfyuiApi.class);
    }

    @Bean
    public ComfyuiMessageHandler comfyuiMessageHandler() {
        return new ComfyuiMessageHandler();
    }

    @Bean
    public WebSocketConnectionManager webSocketConnectionManager(ComfyuiMessageHandler comfyuiMessageHandler){
        // 创建一个 webSocket客户端
        WebSocketClient webSocketClient = new StandardWebSocketClient();
        //定义服务端地址
        String url = "ws://127.0.0.1:8188/ws?clientId=star-graph";
        //创建一个连接管理器
        WebSocketConnectionManager webSocketConnectionManager = new WebSocketConnectionManager(webSocketClient, comfyuiMessageHandler, url);
        webSocketConnectionManager.start();
        return webSocketConnectionManager;

    }
}
